<?php
// defined('IN_ZEEGING') or die('Access Denied');
ini_set('display_errors', 'on');
class BOApi{
	
	//私有变量
	private $adminUser="webmaster";
    private $adminPass="webmaster";
    private $cookies;

    const DEPOSITTYPE_WITHDRAWABLE=1;
    const DEPOSITTYPE_NONWITHDRAWABLE=2;
    const DEPOSITTYPE_BONUS=3;
	
    //参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
    protected function curl_request($url,$post='',$cookie='', $returnHeader=1 ,$headers=array()){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://adminkit.bybrain.cn/sign-in/login");
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnHeader);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            print_r('aaaa');
            return curl_error($curl);
        }
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if($returnHeader){
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie']  = isset($matches[1])?$matches[1]:null;
            $info['content'] = $body;
            $info['httpheader'] = explode("\r\n", $header);
            $info['httpcode'] = $httpCode;
            return $info;
        }else{
            return $data;
        }
    }

	public function indexAction(){
		print_r('ERROR');
	}

	private function formatPostData($post_data){
		$o="";
		foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        return substr($o,0,-1);
	}
    protected function GET($key=NULL){
        if(isset($key)){
            return isset($_GET[$key]) ? $_GET[$key] : NULL;
        }
        else{
            return $_GET;
        }
    }
    protected function POST($key=NULL){
        if(isset($key)){
            return isset($_POST[$key]) ? $_POST[$key] : NULL;
        }
        else{
            return $_POST;
        }
    }
    protected function REQUEST($key){
        return isset($_REQUEST[$key]) ? $_REQUEST[$key] : NULL;
    }

    protected function getPath(){
        if(isset($_SERVER['PATH_INFO'])){
            return $_SERVER['PATH_INFO'];
            // return $path=trim($_SERVER['PATH_INFO'],'/');
        }
        else{
            return null;
        }
    }
	
	public function routerAction(){
		//$betCount=50;//注数
		$param=$this->POST(); //简单验证，后续需要完善容错
		$path=$this->getPath();
        $query=$this->GET();
        $queryStr=$this->formatPostData($query);
        if(!empty($query)){
            $apiUrl=$path.'?'.$queryStr;
        }
        else{
            $apiUrl=$path;
        }
        
        $serverName = $this->model=='LIVE' ? $this->liveDomain : $this->devDomain;

        $fullUrl=$serverName.$apiUrl;
        //$url='http://www.multilotto.com/'
        //$post_data['currency']='EUR';
        // print_r($apiUrl);
        // print_r($fullUrl);
        // exit();
        if(!empty($param)){
            $res= $this->curl_request($fullUrl,$param,1);
        }
        else{
            $res = $this->curl_request($fullUrl,'',1); 
        }
		
              
        //print_r($url);
        header($res['httpheader'][0]);
		print_r($res['content']);
	}
    protected function login(){
        $loginPage=$this->curl_request('http://adminkit.bybrain.cn/sign-in/login');
        $loginPageCookie=implode(';', $loginPage['cookie']);
        preg_match("/name=\"_csrf\" value=\"(.*?)\"/", $loginPage['content'], $matches);
        $csrf=$matches[1];
        //exit();
        $loginRes=$this->curl_request('http://adminkit.bybrain.cn/sign-in/login',array(
            "_csrf"=>$csrf,
            "LoginForm[username]"=>$this->adminUser,
            "LoginForm[password]"=>$this->adminPass,
            "LoginForm[rememberMe]"=>"0",
            "login-button"=>""
        ),$loginPageCookie,1,array(
            "Origin"=>"http://adminkit.bybrain.cn"
        ));
        $returnContent=json_decode($loginRes['content']);
        if($loginRes['httpcode']==200 && $returnContent->status==1 && $returnContent->message=="验证成功"){
            $adminCookies=implode(';', $loginPage['cookie']);
            $this->cookies=$adminCookies;
            // print_r($adminCookies);
            return $adminCookies;
        }
        else if($loginRes['httpcode']==302){
            $adminCookies=implode(';', $loginRes['cookie']);
            $this->cookies=$adminCookies;
            return $adminCookies;
            // $loginRes=$this->curl_request('http://adminkit.bybrain.cn','',implode(';', $loginRes['cookie']));
            // print_r($loginRes);
        }
        else{
            return false;
        }
    }
    public function deposit($mobile,$amount,$type){
        /*
        接口格式：
        "/football/account/account-recharge",
        {'mobile':mobile,
            'cash':cash,
            'type':type,    // 充值可提现余额:1、不可提现余额:2、红包金额:3
        }
        */
        // 先登录
        if($cookie=$this->login()){
            // 带着登录态请求充值页面，取得csrf参数
            $depositPage=$this->curl_request('http://adminkit.bybrain.cn/account/recharge','',$this->cookies);
            //name="csrf-token" content="Oj7t1X42nkvoUdinn7nEzl0EsZ3AQFV376ZrBCyOBOoLC4SCPV_3LYMd4e7T9JGPDmzp8pQkFATewV9Sc9xH3g=="
            preg_match("/name=\"csrf\-token\" content=\"(.*?)\"/", $depositPage['content'], $matches);
            $csrf=$matches[1];
            // 带着csrf参数请求充值接口
            $depositRes=$this->curl_request('http://adminkit.bybrain.cn/account/recharge',array(
                    "mobile"=>$mobile,
                    "cash"=>$amount,
                    "type"=>$type
            ),$this->cookies,1,array(
                "X-Requested-With: XMLHttpRequest",
                "X-CSRF-Token: ".$csrf
            ));
            $returnContent=json_decode($depositRes['content']);
            if($depositRes['httpcode']==200 && $returnContent->status==1 && $returnContent->message=="充值成功"){
                print_r($depositRes['content']);
                return true;
            }
            else{
                return false;
            }
        }
        else{
            return false;
        }
    }
}

// $api=new BOApi();
// $api->deposit('17665343247',5,1);
//------------------------------------------------
//End of File : /Api.php
//------------------------------------------------